package com.example.javachatroomextend.controller;

import com.example.javachatroomextend.constant.Constant;
import com.example.javachatroomextend.model.Result;
import com.example.javachatroomextend.model.User;
import com.example.javachatroomextend.service.UserService;
import com.example.javachatroomextend.utils.TikaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result<Boolean> login(String username, String password, HttpServletRequest request) {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail(404,false,"账号或者密码为空，请检查后再试吧！");
        }
        User user = userService.getUserByName(username);
        if (user == null || user.getUserId() < 0) {
            return Result.fail(404,false,"该用户不存在，请注册后再试吧");
        }
        if (!password.equals(user.getPassword())) {
            return Result.fail(404,false,"账号或者密码错误");
        }else {
            HttpSession session = request.getSession();
            user.setPassword("");
            session.setAttribute("user",user);
            return Result.success(true);
        }
    }

    @Transactional
    @RequestMapping("/registry")
    public Result<Boolean> registry(String username, String password, String repassword, @RequestParam("file") MultipartFile file) throws IOException {
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)
        ||!StringUtils.hasLength(repassword) || file == null) {
            log.info("username:" + username);
            log.info("password:" + password);
            log.info("repassword:" + repassword);
            log.info("file" + file.toString());
            return Result.fail(404,false,"用户名、密码、确认密码、或者头像为空！");
        }
        if (!password.equals(repassword)) {
            return Result.fail(404,false,"两次输入的密码不同，请确认后再试！");
        }
        User user = userService.getUserByName(username);
        if (user != null && user.getUserId() >= 0) {
            return Result.fail(404,false,"该用户已存在，请确认后再试一下吧！");
        }
        String type = file.getContentType();
        int index = file.getOriginalFilename().lastIndexOf(".");
        String last = file.getOriginalFilename().substring(index);
        String fileName = username + last;
        for (String t : Constant.imagesType) {
            if (type.equals(t)) {
                file.transferTo(new File(Constant.path + fileName));
                int ret = userService.addUser(username,password,fileName);
                if (ret < 0) {
                    log.info("addUser的时候出现错误");
                    return Result.fail(500,false,"服务器内部出现错误，请联系管理员");
                }
                return Result.success(true);
            }
        }
        return Result.fail(404,false,"上传的文件不属于图片类型！");
    }

    @RequestMapping("/getUserInfo")
    public Result<User> getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        user.setPassword("");
        return Result.success(user);
    }

    @RequestMapping("/getUserPic")
    public ResponseEntity<Resource> getUserPic(String fileName) {
        Resource resource = new FileSystemResource(Constant.path + fileName);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)
                .header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=" + resource.getFilename())
                .body(resource);
    }
}
